<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>优先级队列-基于数组的优先级队列封装</title>
</head>
<body>
  <script>
    /**
      通过优先级指数进行比较，指数越小，优先级越高
      对原有元素依次比较，然后进行插入，优先级最小的插入到最后
    */
    function PriorityQueue () {
      
      this.items = [];
      PriorityQueue.prototype.enQueue = function (ele, p) {
        // 判断数组是否为空，为空时直接插入
        if (!this.items.length) {
          return this.items.push(`${ele}-p${p}`);
        }
        const mapPriorityArr = this.items.map(item => item.split('-p')[1]);
        let isEnqueue = false;
        for (const [index, originP] of Object.entries(mapPriorityArr)) {
          if (p <= originP) {
            isEnqueue = true;
            this.items.splice(index, 0, `${ele}-p${p}`); // 插入优先级高的元素
            return;
          }
        }
        // 优先级最低的插入到奥最后
        if (!isEnqueue) this.items.push(`${ele}-p${p}`);
      }

      // deQueue，出队列
      PriorityQueue.prototype.deQueue = function () {
        return this.items.shift();
      }

      // front，查看队列的第一个元素
      PriorityQueue.prototype.front = function () {
        return this.items[0];
      }

      // isEmpty,查看队列是否为空
      PriorityQueue.prototype.isEmpty = function () {
        return this.items.length > 0;
      }

      // size,查看队列的个数
      PriorityQueue.prototype.size = function () {
        return this.items.length;
      }

      // toString,将队列元素转换为字符串
      PriorityQueue.prototype.toString = function () {
        return this.items.map(ele => ele.toString());
      }
    }
    const pq = new PriorityQueue();
    pq.enQueue('cs', 10);
    pq.enQueue('cj', 6);
    pq.enQueue('cc', 8);
    pq.enQueue('cl', 1);
    pq.enQueue('ck', 8);
    console.log(pq);
  </script>
</body>
</html>